package com.hctforgreen.greenservice.ui.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.MyFeedbackActivity;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ShowMegaImageActivity;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BaseEntity;
import com.hctforgreen.greenservice.model.FeedBackListEntity.FeedBackEntity;
import com.hctforgreen.greenservice.model.FeedBackMessageEntity;
import com.hctforgreen.greenservice.model.ResultEntity;
import com.hctforgreen.greenservice.ui.handler.FeedBackListHandler;
import com.hctforgreen.greenservice.ui.handler.OpenCaseListHandler;
import com.hctforgreen.greenservice.ui.page.AbstractDataLoaderHandler;
import com.hctforgreen.greenservice.ui.page.AbstractPageableAdapter;
import com.hctforgreen.greenservice.utils.AsyncImageLoader;
import com.hctforgreen.greenservice.utils.AsyncImageLoader.ImageCallback;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.KeyboardUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.Md5Util;
import com.hctforgreen.greenservice.utils.Utils;

public class OpenCaseListAdapter extends AbstractPageableAdapter<BaseEntity>
		implements OnItemClickListener {

	private Activity mActivity;
	private View mConvertView;
	private ListView mListView;
	private OpenCaseListHandler mHandler;

	public OpenCaseListAdapter(ListView listView, Activity activity,
			View convertView, int loadingViewResourceId,
			int reloadViewResourceId,
			AbstractDataLoaderHandler<BaseEntity> handler) {
		super(listView, activity, loadingViewResourceId, reloadViewResourceId,
				handler);
		mListView = listView;
		mActivity = activity;
		mConvertView = convertView;

		mHandler = (OpenCaseListHandler) handler;
		mListView.setAdapter(this);
		mListView.setOnItemClickListener(this);
		mListView.setOnScrollListener(this);
		mListView.setDivider(mActivity.getResources().getDrawable(
				R.drawable.ic_driver));
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewCache viewCache;
		final FeedBackEntity entity = (FeedBackEntity) getItem(position);
		if (convertView == null) {
			convertView = View.inflate(mActivity, R.layout.item_open_case_lst,
					null);
			viewCache = new ViewCache(convertView);
			convertView.setTag(viewCache);
		} else {
			viewCache = (ViewCache) convertView.getTag();
		}

		viewCache.getSeriesNameTv().setText(entity.seriesName);
		viewCache.getSubmitDateTv().setText(entity.submitDate);
		viewCache.getContentTv().setText(
				mActivity.getString(R.string.feedback_adapter_content_tag)
						+ entity.content);
		viewCache.getTitleTv().setText(
				mActivity.getString(R.string.feedback_adapter_theme_tag)
						+ entity.title);

		initMsgList(viewCache, entity);

		// if (entity.answerContent == null
		// || "".equals(entity.answerContent.trim())) {
		// viewCache.getAnswerContentTv().setText("暂无回复");
		// viewCache.getAnswerNameTv().setText("");
		// viewCache.getTvTag().setVisibility(View.GONE);
		// } else {
		// viewCache.getAnswerContentTv().setText(entity.answerContent);
		// viewCache.getAnswerNameTv().setText("回复"/* entity.answerName */);
		// viewCache.getTvTag().setVisibility(View.VISIBLE);
		// }

		renderPicLayout(viewCache, entity);

		return convertView;
	}

	private void initMsgList(ViewCache cache, FeedBackEntity entity) {
		if (entity.msgs.isEmpty()) {
			cache.getSubListView().removeAllViews();
			cache.getMsgView().setVisibility(View.GONE);
			return;
		}
		cache.getSubListView().removeAllViews();
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		for (FeedBackMessageEntity messageEntity : entity.msgs) {
			View convertView = View.inflate(mActivity,
					R.layout.item_feed_back_message, null);

			TextView name = (TextView) convertView
					.findViewById(R.id.tv_answer_name);
			TextView content = (TextView) convertView
					.findViewById(R.id.tv_answer_content);
			LinearLayout picLayout = (LinearLayout) convertView
					.findViewById(R.id.lyt_pic_parent);
			if ("0".equals(messageEntity.messageType)) {// 系统回复
				name.setText(mActivity
						.getString(R.string.feedback_message_system_reply));
				name.setTextColor(Color.BLUE);
			} else {// 我的回复
				name.setText(mActivity
						.getString(R.string.feedback_message_self_reply));
				name.setTextColor(Color.rgb(255, 115, 21));
			}
			content.setText(messageEntity.messageContent);

			if (messageEntity.messagePicPath != null
					&& !"".equals(messageEntity.messagePicPath.trim())) {
				renderPicLayout(picLayout, messageEntity);
			}
			cache.getSubListView().addView(convertView, params);
		}
		cache.getSubListView().setVisibility(View.VISIBLE);
		cache.getMsgView().setVisibility(View.VISIBLE);
	}

	private void renderPicLayout(LinearLayout picLayout,
			FeedBackMessageEntity entity) {

		// if (viewCache.getPicParentTv().getChildCount() == 0) {
		// for (int i = 0; i < 6; i++) {
		FrameLayout choiceLyt = (FrameLayout) mActivity.getLayoutInflater()
				.inflate(R.layout.layout_pic, null);
		choiceLyt.setId(1+333);
		if (picLayout.getChildCount() == 0) {
			picLayout.addView(choiceLyt, 0);
		}
		// }
		// }
		//
		// int iFreeSize = 6 - entity.picNames.size();
		// if (iFreeSize > 0) {
		// for (int i = 5; i > entity.picNames.size() - 1; i--) {
		// FrameLayout choiceLyt = (FrameLayout) viewCache
		// .getPicParentTv().findViewById(i);
		//
		// choiceLyt.setVisibility(View.GONE);
		//
		// }
		// // }
		// FrameLayout choiceLyt = (FrameLayout) mActivity.getLayoutInflater()
		// .inflate(R.layout.layout_pic, null);
		choiceLyt.setVisibility(View.VISIBLE);
		// viewCache.getPicParentTv().addView(choiceLyt);
		renderPicIv(entity.messagePicPath, choiceLyt);
		// viewCache.getPicParentTv().addView(choiceLyt);

	}

	private View initFooterView(final FeedBackEntity entity, final int position) {

		View footView = mActivity.getLayoutInflater().inflate(
				R.layout.feed_back_message_footer, null);
		final View editView = footView.findViewById(R.id.layout_reply);
		editView.setVisibility(View.GONE);
		final EditText edtMsg = (EditText) footView
				.findViewById(R.id.edt_message);
		final TextView tvReply = (TextView) footView
				.findViewById(R.id.text_reply);

		final ImageView imgPraise = (ImageView) footView
				.findViewById(R.id.img_praise);
		final ImageView imgStamp = (ImageView) footView
				.findViewById(R.id.img_stamp);
		ImageView imgReply = (ImageView) footView.findViewById(R.id.img_reply);

		if ("0".equals(entity.score)) {
			imgPraise.setBackgroundResource(R.drawable.feedback_praise_pressed);
		}

		if ("1".equals(entity.score)) {
			imgStamp.setBackgroundResource(R.drawable.feedback_stamp_pressed);
		}

		// 显示/隐藏回复view
		imgReply.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (editView.getVisibility() == View.VISIBLE) {
					editView.setVisibility(View.GONE);
					try {
						KeyboardUtil.hideSoftKeyboard(mActivity);
					} catch (Exception e) {
						// TODO: handle exception
					}
				} else {
					editView.setVisibility(View.VISIBLE);
					try {
						// KeyboardUtil.showSoftKeyboard(mActivity);
						mActivity
								.getWindow()
								.setSoftInputMode(
										WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

					} catch (Exception e) {
						e.printStackTrace();
					}
					edtMsg.requestFocus();
				}
			}
		});
		// 顶
		imgPraise.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ("".equals(entity.score)) {
					feedbackScore(entity, "0", imgPraise, position);
				} else {
					Toast.makeText(mActivity,
							mActivity.getString(R.string.feedback_have_score),
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		// 踩
		imgStamp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if ("".equals(entity.score)) {
					feedbackScore(entity, "1", imgStamp, position);
				} else {
					Toast.makeText(mActivity,
							mActivity.getString(R.string.feedback_have_score),
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		// 回复
		tvReply.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final String msg = edtMsg.getText().toString();
				if (msg.trim().equals("")) {
					Toast.makeText(
							mActivity,
							mActivity.getString(R.string.feedback_message_hint),
							Toast.LENGTH_SHORT).show();
					return;
				}

				tvReply.setClickable(false);
				final Handler handler = new Handler() {
					public void handleMessage(Message msg) {
						tvReply.setClickable(true);

						HctResult hctResult = new HctResult();
						switch (msg.what) {
						case HctConstants.STATUS_SUCCESS:
							Utils.submitPoints(mActivity, 1, "", false);

							hctResult = (HctResult) msg.obj;
							ResultEntity entity = (ResultEntity) hctResult.data;
							if (entity.statusCode.equals("0")) {
								try {
									KeyboardUtil.hideSoftKeyboard(mActivity);
								} catch (Exception e) {
								}
								MyFeedbackActivity activity = (MyFeedbackActivity) mActivity;
								if (activity != null) {
									activity.initWindow();
								}
							} else if (!entity.statusCode.equals("0")) {

								Toast.makeText(mActivity, entity.msg,
										Toast.LENGTH_SHORT).show();
							}
							break;

						case HctConstants.STATUS_FAILD:
							Toast.makeText(
									mActivity,
									mActivity
											.getString(R.string.net_error_hint),
									Toast.LENGTH_SHORT).show();
							break;
						}
					}
				};
				new Thread() {
					public void run() {
						Message message = new Message();
						try {
							HctController controller = new HctController(
									mActivity);
							HctResult result = controller.addFeedbackMessage(
									LoginResultStoreUtil.get(mActivity).personId,
									entity.id, msg);

							if (result.status == HctConstants.STATUS_SUCCESS) {
								message.what = result.status;
								message.obj = result;
							} else {
								message.what = HctConstants.STATUS_FAILD;
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						handler.sendMessage(message);
					}
				}.start();
			}

		});
		return footView;
	}

	//
	private void feedbackScore(final FeedBackEntity backEntity,
			final String score, final ImageView btn, final int position) {

		btn.setClickable(false);
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				btn.setClickable(true);

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					hctResult = (HctResult) msg.obj;
					ResultEntity entity = (ResultEntity) hctResult.data;
					if (entity.statusCode.equals("0")) {
						Toast.makeText(
								mActivity,
								mActivity
										.getString(R.string.feedback_score_success),
								Toast.LENGTH_SHORT).show();
						backEntity.score = score;
						if (btn.getId() == R.id.img_praise) {
							btn.setBackgroundResource(R.drawable.feedback_praise_pressed);
						} else if (btn.getId() == R.id.img_stamp) {
							btn.setBackgroundResource(R.drawable.feedback_stamp_pressed);
						}
						getmList().set(position, backEntity);
						notifyDataSetChanged();
					} else if (!entity.statusCode.equals("0")) {
						Toast.makeText(mActivity, entity.msg,
								Toast.LENGTH_SHORT).show();
					}
					break;

				case HctConstants.STATUS_FAILD:
					Toast.makeText(mActivity,
							mActivity.getString(R.string.net_error_hint),
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		};
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);
					HctResult result = controller.submitScore(backEntity.id,
							score);

					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();

	}

	/**
	 * 2016 12 8 390778
	 *暂时解决android studio打包问题
	 * choiceLyt.setId(i+0);
	 * 动态添加控件时需要设置id，
	 * 在当前的activity界面上id要保证唯一
	 * （i+0）修改不严谨，需要进行优化
	 * @param viewCache
	 * @param entity
     */
	private void renderPicLayout(final ViewCache viewCache,
			final FeedBackEntity entity) {

		if (viewCache.getPicParentTv().getChildCount() == 0) {
			for (int i = 0; i < 6; i++) {
				FrameLayout choiceLyt = (FrameLayout) mActivity
						.getLayoutInflater().inflate(R.layout.layout_pic, null);
				choiceLyt.setId(i+0);
				viewCache.getPicParentTv().addView(choiceLyt, i);
			}
		}

		int iFreeSize = 6 - entity.picNames.size();
		if (iFreeSize > 0) {
			for (int i = 5; i > entity.picNames.size() - 1; i--) {
				FrameLayout choiceLyt = (FrameLayout) viewCache
						.getPicParentTv().findViewById(i+0);

				choiceLyt.setVisibility(View.GONE);
			}
		}
		for (int i = 0; i < entity.picNames.size(); i++) {
			if (!"".equals(entity.picNames.get(i).trim())) {
				String sPicName = buildPicUrl(entity, i);
				FrameLayout choiceLyt = (FrameLayout) viewCache
						.getPicParentTv().findViewById(i+0);
				choiceLyt.setVisibility(View.VISIBLE);
				renderPicIv(sPicName, choiceLyt);
			}
		}

	}

	private String buildPicUrl(final FeedBackEntity entity, int i) {
		return HctConstants.NET_URL
				+ "opencase-mobile!getOpencasePicByName.do?id=" + entity.id
				+ "&picName=" + entity.picNames.get(i);
	}

	private void renderPicIv(final String sPicName, final FrameLayout choiceLyt) {
		final ImageView choiceIv = (ImageView) choiceLyt
				.findViewById(R.id.iv_choice);
		choiceIv.setTag(Md5Util.md5(sPicName));
		AsyncImageLoader imageLoader = new AsyncImageLoader();
		Drawable cacheDrawable = imageLoader.loadDrawable(sPicName, mActivity,
				true, new ImageCallback() {

					@Override
					public void imageLoaded(Drawable imageDrawable,
							String imageUrl) {
						ImageView tagImage = (ImageView) choiceLyt
								.findViewWithTag(imageUrl);
						if (tagImage != null) {
							if (imageDrawable != null) {
								tagImage.setImageDrawable(imageDrawable);
							} else {
								tagImage.setImageResource(R.drawable.ic_default_pic);
							}
						}

					}
				});
		if (cacheDrawable != null) {
			choiceIv.setImageDrawable(cacheDrawable);
		} else {
			choiceIv.setImageResource(R.drawable.ic_default_pic);
		}
		choiceIv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.putExtra("image", sPicName);
				intent.setClass(mActivity, ShowMegaImageActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				mActivity.startActivity(intent);
				// Toast.makeText(mActivity, sPicName,
				// Toast.LENGTH_SHORT).show();
			}
		});
	}

	class ViewCache {
		private View baseView;
		private TextView submitDate;
		private TextView title;
		private TextView content;
		private TextView seriesName;
		private LinearLayout picParent;
		private LinearLayout subListView;

		private View msgView;

		private ImageView imgState;

		public ViewCache(View view) {
			baseView = view;
		}

		public View getMsgView() {

			if (msgView == null) {
				msgView = baseView.findViewById(R.id.layout_message);
			}
			return msgView;
		}

		public ImageView getImgState() {
			if (imgState == null) {
				imgState = (ImageView) baseView
						.findViewById(R.id.img_hide_show);
			}
			return imgState;
		}

		public LinearLayout getSubListView() {
			if (subListView == null) {
				subListView = (LinearLayout) baseView
						.findViewById(R.id.msg_list);
			}

			return subListView;
		}

		public TextView getSubmitDateTv() {
			if (submitDate == null) {
				submitDate = (TextView) baseView
						.findViewById(R.id.tv_submit_date);
			}
			return submitDate;
		}

		public TextView getTitleTv() {
			if (title == null) {
				title = (TextView) baseView.findViewById(R.id.tv_title);
			}
			return title;
		}

		public TextView getContentTv() {
			if (content == null) {
				content = (TextView) baseView.findViewById(R.id.tv_content);
			}
			return content;
		}

		public TextView getSeriesNameTv() {
			if (seriesName == null) {
				seriesName = (TextView) baseView
						.findViewById(R.id.tv_series_name);
			}
			return seriesName;
		}

		public LinearLayout getPicParentTv() {
			if (picParent == null) {
				picParent = (LinearLayout) baseView
						.findViewById(R.id.lyt_pic_parent);
			}
			return picParent;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
	}

}
